package com.haoziqi.chapter_01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * description
 * TODO 有界流,处理文本数据 使用flatmap+keyby+sum
 * created by A on 2021/3/2
 */
public class StreamDemo {
    public static void main(String[] args) throws Exception {
      //1.创建流式执行环境
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        //2.读取文件
        DataStreamSource<String> dss = senv.readTextFile("input/word.txt");
        //3.处理数据
        SingleOutputStreamOperator<Tuple2<String, Long>> sos = dss.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] s1 = s.split(" ");
                for (String s2 : s1) {
                    collector.collect(Tuple2.of(s2, 1L));
                }
            }
        });
        //3.1将数据按照key进行分组
        KeyedStream<Tuple2<String, Long>, Tuple> ks = sos.keyBy(0);
        //3.2将每组内的数据聚合
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = ks.sum(1);
        //4.打印
        sum.print();
        //5.执行
        senv.execute();
    }
}
